package com.sys.customer.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sys.customer.domain.SysUserSpecialty;
import com.sys.customer.mapper.SysUserSpecialtyMapper;
import com.sys.customer.service.SysUserSpecialtyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LGY
 * Create by 2025/2/20 11:28
 */
@Service
public class SysUserSpecialtyServiceImpl extends ServiceImpl<SysUserSpecialtyMapper, SysUserSpecialty> implements SysUserSpecialtyService {

    @Override
    public List<SysUserSpecialty> findByUserId(String userId) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .eq(SysUserSpecialty::getUserId, userId)
                .list();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveUserSpecialty(List<SysUserSpecialty> userSpecialtyList,String userId) {
       // 先删除所有数据
        new LambdaUpdateChainWrapper<>(baseMapper)
                .eq(SysUserSpecialty::getUserId,userId)
                .remove();
        // 保存数据
        if (!CollectionUtils.isEmpty(userSpecialtyList)) {
            List<SysUserSpecialty> saveData = userSpecialtyList.stream().map(item -> {
                SysUserSpecialty sysUserSpecialty = new SysUserSpecialty();
                sysUserSpecialty.setUserId(userId);
                sysUserSpecialty.setName(item.getName());
                sysUserSpecialty.setValue(item.getValue());
                sysUserSpecialty.setStyle(item.getStyle());
                return sysUserSpecialty;
            }).toList();
            this.saveBatch(saveData);
        }
    }
}
